<template>
	<view class="pd-b-200">
		<view class="container">
			<view class="flex-row row-column row-middle box" @click="scanCode">
				<u-icon name="scan" color="#06A972" size="80"></u-icon>
				<text>扫描包装盒上正品认证二维码</text>
			</view>
			<view class="pd-tb-20">
				<u--input placeholder="请扫描包装盒上正品认证二维码" border="surround" v-model="flowCode"></u--input>
			</view>

			<!-- <view class="pd-tb-20">
				<view class="pd-5">车牌号</view>
				<view class="flex-row row-middle" @click="show = true">
					<u-code-input space="5" :focus="true" v-model="plate" :maxlength="maxLength" size="70"
						disabled-keyboard></u-code-input>
					<view class="jia" v-if="maxLength == 7" @click.stop="maxLength = 8">+</view>
					<view class="jia" v-else @click.stop="cancel">-</view>
				</view>
			</view>

			<view class="pd-tb-10">
				<view class="pd-5">车型</view>
				<u-input placeholder="请选择车辆品牌" border="surround" v-model="keyword">
					<template slot="suffix">
						<view class="text-green" @click="searchModel">搜索</view>
					</template>
				</u-input>
			</view>


			<view class="pd-tb-10">
				<view class="pd-5">汽车前脸全身照（机盖上摆放产品包装盒）</view>
				<u-upload :fileList="productList" @afterRead="afterRead" @delete="deletePic" name="productList" multiple
					:maxCount="maxCount" :width="218" :height="218" :accept="accept"></u-upload>
			</view>

			<view>
				<view class="pd-5">产品包装盒</view>
				<u-upload :fileList="frontList" @afterRead="afterRead" @delete="deletePic" name="frontList" multiple
					:maxCount="maxCount" :width="218" :height="218" :accept="accept"></u-upload>
			</view> -->
			<view v-if="detail.categoryId">
				<view class="table" style="width: 100%;">
					<view class="tr">
						<view class="td label">产品型号</view>
						<view class="td value">{{detail.productName}}</view>
					</view>
					<view class="tr">
						<view class="td label">防伪编码</view>
						<view class="td value">{{detail.flowCode}}</view>
					</view>
					<view class="tr">
						<view class="td label">授权区域</view>
						<view class="td value">{{detail.customerArea}}</view>
					</view>
					<view class="tr">
						<view class="td label">所属客户</view>
						<view class="td value">{{detail.customerName}}</view>
					</view>
					<view class="tr">
						<view class="td label">出库时间</view>
						<view class="td value">{{detail.outTime}}</view>
					</view>
					<view class="tr">
						<view class="td label">质保开启</view>
						<view class="td value">{{ newTime }}</view>
					</view>
					<view class="tr">
						<view class="td label">质保时间</view>
						<view class="td value">{{detail.vid}}</view>
					</view>
					<view class="tr">
						<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="fileList"
							multiple :maxCount="maxCount" :width="240" :height="240" ></u-upload>
					</view>
				</view>
			</view>

			<view class="footer">
				<u-button @click="saleActive" text="生成电子保单" color="#06A972"></u-button>
			</view>
			<u-keyboard :safe-area-inset-bottom="true" ref="uKeyboard" :tooltip="false" mode="car" :dotDisabled="true"
				:show="show" @change="onChange" @backspace="onBackspace" @close="show = false">
			</u-keyboard>


			<!--选择车品牌 -->
			<!-- <u-popup :show="showPicker" @close="hidePicker">
				<view class="flex-row row-right pd-20 text-green" @click="confirm">确定</view>
				<picker-view :indicator-style="indicatorStyle" :value="value" @change="bindChange" class="picker-view">
					<picker-view-column>
						<view class="item" v-for="(item,index) in listModel" :key="index">{{item.showName}}</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in listModel[pickerBrandIndex].models" :key="index">
							{{item.modelName}}
						</view>
					</picker-view-column>
					<picker-view-column>
						<view class="item" v-for="(item,index) in yearList" :key="index">{{item.carYear}}</view>
					</picker-view-column>
				</picker-view>
			</u-popup> -->
		</view>
	</view>
</template>


<script>
	import {
		mapGetters
	} from "vuex";
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';
	import formData from '@/utils/formData';
	import {
		getKey,
		getModelDetail
	} from '@/api/car.js';
	import {
		wxCodeDetail
	} from '@/api/common.js';
	export default {
		data() {
			return {
				maxCount: 1,
				flowCode: '',
				productList: [],
				frontList: [],
				fileList: [],
				plate: '',
				maxCount: 1,
				accept: 'video',
				show: false,
				maxLength: 7,
				modelId: '',
				carYear: '',
				showPicker: false,
				keyword: '',
				listModel: [],
				yearList: [],
				indicatorStyle: `height: 50px;`,
				pickerBrandIndex: 0,
				pickerModelIndex: 0,
				detail: {},
				newTime: this.generateNewTime(),
			}

		},

		computed: mapGetters(['isLogin', 'uid']),

		onLoad() {
			if (this.isLogin == false) {
				toLogin();
			}
		},

		onShow() {


		},
		mounted() {
			// 每秒更新一次当前时间
			this.timer = setInterval(() => {
				this.newTime = this.generateNewTime();
			}, 1000);
		},
		beforeDestroy() {
			// 页面销毁时清除定时器
			clearInterval(this.timer);
		},
		methods: {
			generateNewTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			scanCode() {
				let that = this;
				// 允许从相机和相册扫码
				uni.scanCode({
					scanType: ["qrCode"],
					success: (res) => {
						if (res.result) {
							this.flowCode = res.result;
							wxCodeDetail({
								flowCode: this.flowCode,
								userInfoId: that.uid,
							}).then(res => {
								uni.hideLoading();
								that.detail = res.value;
								that.detail.queryList = that.detail.queryList.reverse()
							}).catch(err => {
								that.$util.Tips({
									title: err,
								});
							})
						} else {
							return this.$util.Tips({
								title: '请重新扫描'
							})
						}
					},
					fail: (res) => {
						this.$util.Tips({
							title: '未识别到二维码'
						})
					}
				})
			},

			saleActive() {
				// if (!that.plate) return that.$util.Tips({
				// 	title: '请输入车牌号'
				// });

				// if (!that.modelId) return that.$util.Tips({
				// 	title: '请输入车型'
				// });

				// if (!that.carYear) return that.$util.Tips({
				// 	title: '请输入车年份'
				// });

				// if (that.productList.length < 1) return that.$util.Tips({
				// 	title: '请上传汽车前脸全身照'
				// })

				// if (that.frontList.length < 1) return that.$util.Tips({
				// 	title: '请上产品包装盒'
				// })
				let that = this;
				if (!that.flowCode) return that.$util.Tips({
					title: '请扫描包装盒上正品认证二维码'
				});
				// 检查是否选择了视频文件
				if (that.fileList.length === 0) {
					return that.$util.Tips({
						title: '请上传视频文件'
					});
				}
				uni.showLoading({
					mask: true
				});

				// 构建上传的额外表单数据
				let formData = {
					uid: that.uid,
					signCode: that.flowCode,
					flowCode: that.detail.flowCode,
					productName: that.detail.productName,
					customerArea: that.detail.customerArea,
					specifications: that.detail.specifications,
					customerName: that.detail.customerName,
					outTime: that.detail.outTime
				};
				console.log(HTTP_REQUEST_URL)
				console.log(that.fileList[0].url)
				// uni.uploadFile 进行上传
				uni.uploadFile({
					// url:  'http://localhost:8930/production/insert',//本地调用
					url: HTTP_REQUEST_URL + '/api/production/insert', //正式服调用
					filePath: that.fileList[0].url,
					name: 'shareVideo',
					formData: formData, // 直接传递表单数据
					success: (res) => {
						console.log(res.statusCode)
						// 先检查 HTTP 状态码
						if (res.statusCode === 200) {
							uni.hideLoading();
							that.$util.Tips({
								title: '上传成功',
							});
							// 上传成功后跳转到指定页面
							uni.navigateTo({
								url: '/pages/users/warranty_record/new_index'
							});
						} else {
							// 上传失败（接口返回失败）
							uni.hideLoading();
							that.$util.Tips({
								title: '上传失败（视频大小限制20MB）',
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						that.$util.Tips({
							title: '上传失败',
						});
					}
				});
			},

			// 删除图片
			deletePic(event) {
				this[`${event.name}`].splice(event.index, 1)
			},
			// // 新增图片
			afterRead(event) {
				let that = this;
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				that.list = [].concat(event.file)
				// that.fileListLen = that[`${event.name}`].length
				that.list.map((item) => {
					that[`${event.name}`].push({
						...item,
						status: 'success',
						message: ''
					})
				})
			},

			// 按键被点击(点击退格键不会触发此事件)
			onChange(val) {
				// 将每次按键的值拼接到value变量中，注意+=写法
				// this.plate += val;
				console.log(this.plate.length);
				if (this.plate.length > 7) return
				// 判断是否为 省
				if (this.plate.length < 1) {
					const reg = /^[\u4e00-\u9fa5]$/
					// 正则验证
					const str = reg.test(val)
					if (str) return this.plate += val
				}
				// 判断是否为 英文
				if (this.plate.length == 1) {
					const reg = /^[A-Z_]+$/
					// 正则验证
					const str = reg.test(val)
					if (str) return this.plate += val
				}
				// 判断是否为 英文和数字
				if (this.plate.length > 1 && this.plate.length < this.maxLength) {
					const reg = /^[a-zA-Z0-9_]+$/
					// 正则验证
					const str = reg.test(val)

					if (str) this.plate += val

				}
			},

			// 退格键被点击
			onBackspace() {
				// 删除value的最后一个字符
				if (this.plate.length) this.plate = this.plate.substr(0, this.plate.length - 1);
				console.log(this.plate);
			},

			// 取消新能源车牌
			cancel() {
				this.maxLength = 7;
				if (this.plate.length == 8) this.plate = this.plate.substr(0, this.plate.length - 1);
			},

			/**
			 * 获取车品牌
			 */
			searchModel() {
				let that = this;
				if (!that.keyword) {
					return that.$util.Tips({
						title: '请输入要搜索的品牌'
					});
				}
				getKey({
					keyWord: that.keyword
				}).then(res => {
					that.listModel = res.value;
					that.showPicker = true;
					that.modelId = that.listModel[that.pickerBrandIndex].models[that.pickerModelIndex].modelId;
					that.getModelDetail();
				})
			},

			/**
			 * 获取车型年份
			 */
			getModelDetail(index = 0) {
				let that = this;
				getModelDetail({
					userInfoId: that.uid,
					modelId: that.modelId
				}).then(res => {
					that.yearList = res.value;
					that.carYear = res.value[index].carYear;
				}).catch(err => {

				})
			},

			/**
			 * @param {Object} e
			 * picker 绑定
			 */
			bindChange(e) {
				let that = this;
				that.pickerBrandIndex = e.detail.value[0];
				that.pickerModelIndex = e.detail.value[1];
				that.modelId = that.listModel[that.pickerBrandIndex].models[that.pickerModelIndex].modelId;
				that.getModelDetail(e.detail.value[2])
			},

			/**
			 * 确定
			 */
			confirm() {
				let that = this;
				that.keyword = that.listModel[that.pickerBrandIndex].showName + " " +
					that.listModel[that.pickerBrandIndex].models[that.pickerModelIndex].modelName + " " +
					that.carYear;
				that.showPicker = false;
			},

			/**
			 * 取消
			 */
			hidePicker() {
				let that = this;
				that.showPicker = false;
				that.modelId = that.carYear = '';
				that.pickerBrandIndex = that.pickerModelIndex = 0;
			}
		}
	}
</script>

<style>
	page {
		/* background: #FFF; */
	}

	.container {
		padding: 20rpx 40rpx;
	}

	.box {
		border: 1rpx solid #06A972;
		background-color: #fff;
		padding: 40rpx;
		border-radius: 8rpx;
	}

	.box~.box {
		margin-top: 40rpx;
	}

	.pd-tb-20 {
		padding: 20rpx 0;
	}

	.pd-20 {
		padding: 20rpx;
	}

	.pd-tb-10 {
		padding: 10rpx 0;
	}

	.pd-b-200 {
		padding-bottom: 200rpx;
	}

	.pd-5 {
		padding: 5rpx;
	}

	.u-upload__button {
		/* background-color: #fff !important; */
	}

	.u-upload__button .u-icon__icon {
		font-size: 28px !important;
	}

	.u-upload__deletable__icon .u-icon__icon {
		font-size: 20rpx !important;
		line-height: 20rpx !important;
	}

	.u-upload__success__icon .u-icon__icon {
		font-size: 24rpx !important;
		line-height: 24rpx !important;
	}

	.u-upload__wrap view:nth-child(3n) {
		margin-right: 0rpx;
	}

	.jia {
		padding: 0 20rpx;
		font-size: 50rpx;
	}

	.footre {
		display: block;
	}

	.u-code-input .u-code-input__item text {
		font-size: 32rpx !important;
	}

	.picker-view {
		width: 750rpx;
		height: 400rpx;
		margin-top: 20rpx;
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}

	.table {
		width: 100%;
	}

	.tr {
		display: flex;
		align-items: center;
		border-bottom: 1px solid #eee;
		padding: 10px 0;
	}

	.td {
		flex: 1;
		padding: 5px;
	}

	.label {
		flex: 0.3;
		/* 标签占比 */
		font-weight: bold;
		color: #333;
	}

	.value {
		flex: 0.7;
		/* 值占比 */
		color: #666;
	}
</style>